<template>
  <el-scrollbar wrap-class="scroll-wrapper" style="background-color: #f5f5f5">
    <div class="board-container" id="nav" ref="scrollBox" @mousewheel="handleScroll">
      <div class="type" v-for="(item, index) in templateType" :key="index">
        <!-- 卡片头 -->
        <div
            style="font-size: 15px; font-weight: bold; display: flex; align-items: center; justify-content: space-between; "
        >
          <div>{{ item.typeName }}</div>
          <el-tooltip class="item" effect="dark" content="添加协作项" placement="right">
            <el-button
                style="font-size: 20px;"
                type="text"
                @click="handleAddTask(item)"
            >
              <Icon icon="ep:circle-plus" class="mr-5px"/>
            </el-button>

          </el-tooltip>
        </div>
        <el-divider/>
        <el-scrollbar wrap-class="card-scroll-wrapper" ref="cardScrollRefs">
          <!-- 在这里放置当前状态的卡片池 -->
          <el-card
              v-for="task in getFilteredTasks(item.id)"
              :class="{'card':true,'cardHidden':task.finishState === '已完成'}"
              :key="task.id"
              shadow="hover"
              @mouseover="handleMouseOver"
              @mouseleave="handleMouseLeave"
              @click="handleDetails(task)"
              :body-style="{ padding: '0%' }"
          >
            <div class="card-content">
              <div>
                <a :class="{'text-ellipsis':true,'fontHidden':task.finishState === '已完成'}">
                  <el-badge class="item" type="primary" :value="task.id"/>
                  {{ task.taskName }}
                </a>
                <div :class="{'tagBox':true,'isTagboxHidden': task.finishState === '已完成'}">
                  <span class="text" style="margin: 2px;line-height: 20px;font-size: 11px" v-if="task.executeUser"
                  > {{ task.executeUser_dictText }}</span>
                  <el-link class="text" v-if="task.executeState === '未开始'" type="info">未开始</el-link>
                  <el-link class="text" v-else-if="task.executeState === '进行中'" type="primary">进行中</el-link>
                  <el-link class="text" v-else-if="task.executeState === '已完成'" type="success">已完成</el-link>
                  <el-link class="text" v-else-if="task.executeState === '挂起'" type="danger">挂起</el-link>
                  <el-tag
                      v-if="task.deadline && compareTime(task.deadline, new Date()) === true"
                      size="mini"
                      type="warning"
                  >
                    {{ parseTime(task.deadline, '{m}-{d} {h}:{i}') + '截止' }}
                  </el-tag>
                  <el-tag
                      v-else-if="task.deadline && compareTime(task.deadline, new Date()) === false"
                      size="mini"
                      type="danger"
                  >
                    {{ parseTime(task.deadline, '{m}-{d} {h}:{i}') + '已超时' }}
                  </el-tag>
                </div>
              </div>
              <div class="taskImg">
                <el-tooltip class="item" effect="dark" :content="task.createBy_dictText" placement="right-start">
                  <el-avatar
                      size="small"
                      :src="task.avatar ? task.avatar : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                  />
                </el-tooltip>
              </div>
            </div>
          </el-card>
        </el-scrollbar>
      </div>
    </div>

    <el-drawer
        v-model="open"
        :title="title"
        direction="rtl"
        size="100%"
        :before-close="beforeClose"
    >

      <template #default>
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            style="margin: 10px"
        >
          <el-form-item label="协作标题" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
          </el-form-item>
          <el-form-item label="执行人" prop="executeUser">
            <cascader-user v-model="form.executeUser" placeholder="请输入执行人"/>
          </el-form-item>
          <el-form-item label="截止时间" prop="deadline">
            <el-date-picker
                v-model="form.deadline"
                type="datetime"
                value-format="x"
                placeholder="请选择协作项截止时间"
            />
          </el-form-item>
          <el-form-item label="协作内容" prop="content">
            <editor v-model="form.content" height="300px"/>
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select
                v-model="form.priority"
                placeholder="请选择完成状态"
            >
              <el-option
                  v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_PRIORITY)"
                  :key="dict.value"
                  :value="dict.value"
                  :label="dict.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联文件" prop="taskFile">
            <upload-file v-model="form.taskFile"/>
          </el-form-item>

          <el-form-item label="协助人" prop="assistUser">
            <template #label>
              <div>
                <el-tooltip content="当不清楚协作项执行人时，填写协助人，协作项会被指派" effect="dark">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                <span style="margin-left: 5px;">协助人</span>
              </div>
            </template>
            <cascader-user v-model="form.assistUser" placeholder="请输入执行人"/>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleDrawerClose(false)">取 消</el-button>
          <el-button type="primary" @click="submitForm()" :disabled="formLoading">确定</el-button>
        </div>
      </template>
    </el-drawer>


    <el-dialog
        title="评价"
        v-model="rateVisible"
        :width="size"
    >
      <el-form ref="rateFormRef" :model="form" label-width="100px">
        <el-form-item label="满意程度：" prop="templateImg">
          <el-rate v-model="form.score"/>
        </el-form-item>
        <el-form-item label="评论：" prop="templateImg">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.scoreDesc"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFinish">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <ProjectTaskDetails ref="projectTaskDetailsRef" @success="getList"/>
  </el-scrollbar>
</template>

<script setup>

import {useRoute} from 'vue-router'
import {DICT_TYPE, getDictOptions} from '@/utils/dict'
import {ProjectListApi} from '@/api/business/synergy/project/list'
import {ProjectTemplateApi} from '@/api/business/synergy/project/template'
import {ProjectTaskApi} from '@/api/business/synergy/project/task'
import ProjectTaskDetails from "./components/ProjectTaskDetails.vue";
import {compareTime} from "@/utils/nayun";
import {parseTime} from "../../../../utils/nayun";

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化


const route = useRoute()

// 响应式变量
const templateType = ref([])
const taskList = ref([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const title = ref('')
const rateVisible = ref(false)
const typeId = ref(null)
const scrollBox = ref(null)
const scrollControl = ref(true)
const scrollControlTimer = ref(null)
const size = ref()
const project = ref()
// 表单相关
const formRef = ref(null)
const rateFormRef = ref(null)
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const projectTaskDetailsRef = ref()

// 表单数据
const form = reactive({
  id: null,
  templateId: null,
  projectId: null,
  typeId: null,
  taskName: null,
  finishState: null,
  executeState: null,
  executeUser: null,
  deadline: null,
  content: null,
  priority: null,
  label: null,
  taskFile: null,
  assistUser: null,
  remark: null,
  score: null,
  scoreDesc: null,
  params: {}
})


const {params} = useRoute() // 查询参数
const projectId = params.id
// 路由参数


// 表单验证规则
const rules = reactive({
  taskName: [
    {required: true, message: '请填写协作标题', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '请填写协作内容', trigger: 'blur'}
  ],
  executeUser: [
    {required: true, message: '请选择执行人', trigger: 'blur'}
  ],
})


// 查询参数
const queryParams = reactive({
  pageNum: 1,
  projectId: null
})

// 生命周期钩子
onMounted(() => {
  initData()
})

const getFilteredTasks = (typeId) => {
  return taskList.value.filter(task => task.typeId === typeId)
}

// 初始化数据
const initData = async () => {
  project.value = await ProjectListApi.getProjectList(projectId)
  queryParams.projectId = projectId.value
  const data = await ProjectTemplateApi.getProjectTemplateTypeListByTemplateId(project.value.templateId)
  templateType.value = data
  await getList()
}

// 查询部门协同-任务列列表
const getList = async () => {
  loading.value = true
  queryParams.projectId = projectId
  const data = await ProjectTaskApi.getProjectTaskPage(queryParams)
  taskList.value = data.list
  total.value = data.total
  loading.value = false
}


// 鼠标悬停处理
const handleMouseOver = () => {
  scrollControl.value = false
}

// 鼠标离开处理
const handleMouseLeave = () => {
  scrollControl.value = true
}

// 滚动处理
const handleScroll = (e) => {
  if (scrollControlTimer.value) {
    clearTimeout(scrollControlTimer.value)
  }

  scrollControlTimer.value = setTimeout(() => {
    if (scrollControl.value && scrollBox.value) {
      // deltaY属性在向下滚动时返回正值，向上滚动时返回负值，否则为0
      scrollBox.value.scrollLeft = scrollBox.value.scrollLeft + e.deltaY
    } else if (scrollBox.value) {
      scrollBox.value.style.overflowX = 'hidden'
    }
  }, 50)
}

// 打开添加任务抽屉
const handleAddTask = (row) => {
  resetForm()
  if (row.executeUser) {
    form.executeUser = row.executeUser
  }
  typeId.value = row.id
  open.value = true
  title.value = `添加协作项——${row.typeName}`
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.templateId = null
  form.typeId = null
  form.taskName = null
  form.finishState = null
  form.executeState = null
  form.executeUser = null
  form.deadline = null
  form.content = null
  form.priority = null
  form.label = null
  form.taskFile = null
  form.assistUser = null
  form.remark = null
  form.score = null
  form.scoreDesc = null
  form.params = {}

  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    form.templateId = project.value.templateId
    form.projectId = project.value.id
    form.typeId = typeId.value
    // 处理需求附件（数组转字符串）
    if (Array.isArray(form.taskFile)) {
      form.taskFile = form.taskFile.join(',')
    }
    await ProjectTaskApi.createProjectTask(form)
    message.success(t('common.createSuccess'))
    open.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

// 关闭抽屉
const handleDrawerClose = (value = false) => {
  open.value = value
  if (!value) {
    resetForm()
  }
}

// 关闭前确认
const beforeClose = (done) => {
  ElMessageBox.confirm('确认取消提交吗？').then(() => {
    resetForm()
    done()
  }).catch(() => {
    // 取消关闭
  })
}

// 更新任务完成状态
const updateFinishState = (event, task) => {
  if (task.createBy !== store.getters.userId) {
    message.error('您不是创建者，不能修改状态')
    return
  }
  form.id = task.id
  form.finishState = event ? '已完成' : '未完成'
  rateVisible.value = true
}

// 提交评价
const submitFinish = () => {
  form.params = {column: 'finishState,scoreDesc,score'}
  updateTask(form).then(res => {
    if (res.code === 200) {
      getList()
      message.success(res.msg)
      rateVisible.value = false
    }
  })
}

// 更新任务
const updateTaskHandler = (column) => {
  form.params = {column: column}
  updateTask(form).then(res => {
    if (res.code === 200) {
      getList()
      message.success(res.msg)
    }
  })
}

const handleDetails = (task) => {
  projectTaskDetailsRef.value.showVisible(task)

}

// 导出函数供模板使用
defineExpose({
  updateTaskHandler,
})
</script>

<style scoped>
.scroll-wrapper {
  width: 100%;
  overflow-x: auto;
}

.board-container {
  display: flex;
  padding: 20px 0;
  overflow-x: scroll;
  white-space: nowrap;
}

.type {
  flex-shrink: 0;
  width: 280px; /* 每个状态列的宽度 */
  margin-right: 20px; /* 状态列之间的间距 */
  margin-left: 20px;
  background-color: #f5f5f5;
}

.card-scroll-wrapper {
  height: 1200px; /* 卡片池的高度 */
  overflow-y: auto;
}

.card {
  width: 90%; /* 卡片宽度 */
  height: 100%; /* 卡片高度 */
  margin-bottom: 10px; /* 卡片之间的间距 */
  background-color: #ffffff;
  border-radius: 4px;
  position: relative;
}

.card:before {
  content: "";
  width: 2%;
  height: 100%;
  position: absolute;
  top: 0;
  background-color: #89a9fa;
  border-bottom-left-radius: 25px;
  border-top-left-radius: 25px;
}

.card .card-content {
  width: 98%;
  padding: 2%;
  display: flex;
  flex-direction: row;
}

.card .card-content .taskImg {
  width: 20%;
  height: 30px;
  position: absolute;
  top: 5px;
  right: -5px;
}

.card .card-content a {
  font-size: 14px;
  font-weight: bold;
  margin: 2px;
}

.card .card-content span {
  font-size: 11px;
  margin: 2px;
}

.text-ellipsis {
  width: 180px;
  display: inline-block;
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出部分的文本 */
  text-overflow: ellipsis; /* 使用省略号代替超出部分的文本 */
}

.tagBox {
  max-width: 230px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.el-divider--horizontal {
  margin: 10px;
}

.isTagboxHidden {
  display: none;
}

.cardHidden {
  opacity: 0.6;
  color: rgba(138, 138, 138, 0.87);
}

.fontHidden {
  text-decoration: line-through;
}
</style>
